package com.juzipi.demo.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.juzipi.demo.config.JwtTokenUtil;
import com.juzipi.demo.mapper.UsersMapper;
import com.juzipi.demo.pojo.Users;
import com.juzipi.demo.util.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;


@Service
public class AdminService {


    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("{jwt.tokenHead}")
    private String tokenHead;


    /**
     * 登录之后返回token
     * @param username
     * @param password
     * @param request
     * @return
     */

    public RespBean login(String username, String password, HttpServletRequest request) {
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null||passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号有问题");
        }
        //更新 security 登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token",token);
        hashMap.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",hashMap);

    }



    public Users getAdminByUserName(String username) {

        /**
         * 根据用户名获取用户
         */
        return usersMapper.selectOne(new QueryWrapper<Users>().eq("username",username));

    }
}
